package com.gomore.opple.data.remote.retrofit.interceptor;

import com.gomore.opple.OppleApplication;
import com.gomore.opple.data.DataRepository;
import com.gomore.opple.data.remote.bean.WrapperResponseEntity;
import com.gomore.opple.rest.employee.LoginInfo;
import com.gomore.opple.rest.employee.LoginResult;
import com.gomore.opple.utils.InterceptorUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;

/**
 * Company 上海勾芒科技有限公司.
 */
public class RetryInterceptor implements Interceptor {

    private final int NOT_LOGIN_CODE = 1;
    private final int LOGIN_SUCCESS_CODE = 0;
    private final String CODE = "code";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        try {
            JSONObject jsonObject = new JSONObject(InterceptorUtils.getRspData(response.body()));
            int code = jsonObject.getInt(CODE);
            if (code == NOT_LOGIN_CODE) {
                //获取本地用户信息
                DataRepository dataRepository = OppleApplication.getInstance().getRepositoryComponent().getDataRepository();
                String userName = dataRepository.getUserName();
                String password = dataRepository.getPassWord();

                LoginInfo loginInfo = new LoginInfo();
                loginInfo.setUsername(userName);
                loginInfo.setPassword(password);
                Call<WrapperResponseEntity<LoginResult>> wrapperResponseEntity = dataRepository.loginSyn(loginInfo);
                WrapperResponseEntity<LoginResult> result = wrapperResponseEntity.execute().body();
                //重新保存用户名称和密码
                if (result != null && result.getCode() == LOGIN_SUCCESS_CODE) {
                    LoginResult loginResult = result.getData();
                    dataRepository.saveUser(loginResult);
                    dataRepository.saveUserName(userName);
                    dataRepository.savePassWord(password);
                    response = chain.proceed(request);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }//session 过期后重新登录
}
